﻿/*
 *  Source code courtesy of the desktopWeb.CodePlex.com community project. See MS-PL license on Codeplex.com. 
 *  This is beta code not intended for a production application.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using System.Security.Principal;
using System.Diagnostics;
using MyData.Common.TeamServiceReference;

namespace MyData.Common
{
  public class Permissions
  {
    public class User
    {
      private Permissions _parent;

      public User(Permissions parent)
      {
        _parent = parent;
      }

      public Permissions Parent
      {
        get
        {
          return _parent;
        }
        set
        {
          _parent = value;
        }
      }

      public string Name
      {
        get
        {
          return WindowsIdentity.GetCurrent().Name;
        }
      }

      public bool CanManage
      {
        get
        {
          BasePermissions basePermissions = new BasePermissions();
          basePermissions.Set(PermissionKind.ManageWeb);
          return _parent.DoesUserHavePermissions(basePermissions);
        }
      }
    }

    public string serviceUrl = Properties.Settings.Default.SharePointUrl + @"/_vti_bin/ListData.svc";
    public TeamSiteDataContext DataContext;
    public ClientContext clientContext = new ClientContext(Properties.Settings.Default.SharePointUrl);

    public Permissions()
    {
      DataContext = new TeamSiteDataContext(
        new Uri(serviceUrl, UriKind.Absolute));
      DataContext.Credentials = System.Net.CredentialCache.DefaultCredentials;
    }

    public User CurrentUser
    {
      get
      {
        return new User(this);
      }
    }

    public List<UserInformationListItem> UserInfoList
    {
      get{
        return DataContext.UserInformationList.Execute().ToList();
      }
    }

    public class SimpleUserInformation
    {
      public int Id { get; set; }
      public string Name { get; set; }
      public string Account { get; set; }

    }
    public List<SimpleUserInformation> PersonUserInfoList
    {
      get{
        var q = from u in this.UserInfoList
              where u.ContentType == "Person" & u.Name != "System Account" & u.Name != @"NT AUTHORITY\LOCAL SERVICE"
              select new SimpleUserInformation { Id = u.Id, Name = u.Name, Account = u.Account };
      
        return q.ToList();
      }
    }

    public bool DoesUserHavePermissions(BasePermissions basePermissions)
    {
      Web w = clientContext.Web;

      ClientResult<bool> r = w.DoesUserHavePermissions(basePermissions);

      try
      {
        clientContext.ExecuteQuery();
      }
      catch (Exception ex)
      {
        //Next: Add - Logging.Log(TraceEventType.Error, "DoesUserHavePermissions", ex.Message);
      }

      return r.Value;

    }
  }
}
